<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace Model\Admin;

/**
 * 分类模型
 * @author LazyPHP
 * @version 1.0
 */
class CategoryModel extends CommonModel {

    private static $li = 1, $selected;

    /**
     * 用于特殊的条件筛选查找
     * @var type 
     */
    public static $where = '', $tree = '';

    /**
     * 清空where条件记录
     * 避免脚本执行出错
     */
    private static function clearWhere() {
        self::$where = '';
    }

    /**
     * 获取分类内容(通用类型)
     * @param type $value 查找的值
     * @param type $type 查找的类型|默认为ID
     * @return boolean 提交参数为空时，返回二维数组。参数不为空则返回一维数组。没有结果则返回false;
     */
    public static function getCategory($value = "", $type = "id") {
        return self::GetTableContent($value, $type, 'category');
    }

    /**
     * 获取获取分类(含模型)
     * @param type $value 查找的值
     * @param type $type 查找的类型|默认为ID
     * @return boolean 提交参数为空时，返回二维数组。参数不为空则返回一维数组。没有结果则返回false;
     */
    public static function listCategory($value = "", $type = "id") {
        $db = self::db('category pc');
        if (empty($value)) {
            $result = $db->field('pc.id, pc.cate_name, pc.model_id, pc.parent_id, pc.keyword, pc.description, pc.url, pc.aliases, pc.is_nav, pc.thumb, pc.listsort, pm.model_name, pm.name')->join('pes_model pm on pm.id = pc.model_id')->where(self::$where)->order('listsort asc, id asc')->select();
            self::clearWhere();
            return $result;
        } else {
            $data[$type] = $value;
            //拼合条件
            if (empty(self::$where)) {
                self::$where = "pc.{$type} = :{$type}";
            } else {
                self::$where .= "and pc.{$type} = :{$type}";
            }
            $result = $db->field('pc.id, pc.cate_name, pc.model_id, pc.parent_id, pc.keyword, pc.description, pc.url, pc.aliases, pc.is_nav, pc.thumb, pc.listsort, pm.model_name, pm.name')->join('pes_model pm on pm.id = pc.model_id')->where(self::$where)->find($data);
            self::clearWhere();
            if (empty($result)) {
                return false;
            }
            return $result;
        }
    }

    /**
     * 输出分类列表
     */
    public static function outPutListCate() {
        $list = self::listCategory();
        self::setListCate($list, $list);
        return self::$tree;
    }

    /**
     * 设置列表输出格式
     * @param $array 数组一
     * @param $array_2 数组二
     * @param $id 父类产品ID
     * @param $depth 用于判断递归深度
     * @return
     */
    private static function setListCate($array, $array_2, $id = '0', $depth = '0') {
        $count = count($array_2);
        if ($depth < 3) {
            for ($i = 0; $i < $count; $i++) {
                $array[$i]['name'] = $array[$i]['model_id'] == '-1' ? '外部链接' : $array[$i]['name'];
                $nav = $array[$i]['is_nav'] == '1' ? '是' : '<span class="red">否</span>';
                //记录第一层数据
                if ($id == 0 && $array[$i]['parent_id'] == 0) {
                    self::$tree .= '<tr><td><input class="input length_0" type="text" name="listsort['.$array[$i]['id'].']" value="'.$array[$i]['listsort'].'" /></td><td>' . $array[$i]['cate_name'] . '</td><td>' . $array[$i]['name'] . '</td><td>' . $nav . '</td><td>';
                    self::$tree .= self::catHtml($array[$i]['id']);
                    self::$tree .= '</td></tr>';
                }
                //第二层数据
                foreach ($array as $key => $value) {
                    $value['name'] = $value['model_id'] == '-1' ? '外部链接' : $value['name'];
                    $nav = $value['is_nav'] == '1' ? '是' : '<span class="red">否</span>';
                    self::$li = 0;
                    if ($array[$i]['id'] == $value['parent_id'] && $array[$i]['parent_id'] == 0) {
                        self::$tree .= '<tr><td><input class="input length_0" type="text" name="listsort['.$value['id'].']" value="'.$value['listsort'].'" /></td><td>' . self::plus_none_icon(self::$li) . '<span class="plus_icon plus_end_icon"></span>' . $value['cate_name'] . '</td><td>' . $value['name'] . '</td><td>' . $nav . '</td><td>';
                        self::$tree .= self::catHtml($value['id']);
                        self::setListCate($array[$i], $array_2, $value['id'], 3);
                        self::$tree .= '</td></tr>';
                    }
                }
            }
            //三层及以上的数据进行单独的排序
        } elseif ($depth >= 3) {
            foreach ($array_2 as $depth_key => $depth_value) {
                $depth_value['name'] = $depth_value['model_id'] == '-1' ? '外部链接' : $depth_value['name'];
                $nav = $depth_value['is_nav'] == '1' ? '是' : '<span class="red">否</span>';
                if ($id == $depth_value['parent_id'] && $id > 0) {
                    self::$li++;
                    self::$tree .= '<tr><td><input class="input length_0" type="text" name="listsort['.$depth_value['id'].']" value="'.$depth_value['listsort'].'" /></td><td>' . self::plus_none_icon(self::$li) . '<span class="plus_icon plus_end_icon"></span>' . $depth_value['cate_name'] . '</td><td>' . $depth_value['name'] . '</td><td>' . $nav . '</td><td>';
                    self::$tree .= self::catHtml($depth_value['id']);
                    self::setListCate($array[$i], $array_2, $depth_value['id'], 3);
                    self::$tree .= '</td></tr>';
                    self::$li--;
                }
            }
        }
    }

    /**
     * 创建分类的操作按钮
     * @param type $id 分类ID
     * @return type 返回设置好的字符串
     */
    private static function catHtml($id) {
        $edit = '<a href="/?g=Admin&m=Category&a=edit&id=' . $id . '" class="mr10 btn btn_submit" id="' . $id . '" >编辑</a>';
        $add = '<a href="/?g=Admin&m=Category&a=add&id=' . $id . '" class="mr10 btn btn_submit" id="' . $id . '" >添加下层分类</a>';
        $delete = '<a href="/?g=Admin&m=Category&a=delete&id=' . $id . '" class="mr10 btn btn_submit" id="' . $id . '" onclick="return deleteWarning(this)" >删除</a>';
        return $edit . $add . $delete;
    }

    /**
     * 放置分类的排版空间
     * @param type $frequency 级别
     * @return string 返回设置好的字符串
     */
    private static function plus_none_icon($frequency) {
        $str = '';
        for ($i = 0; $i < $frequency; $i++) {
            $str .='<span class="plus_icon plus_none_icon"></span>';
        }
        return $str;
    }

    /**
     * 输出分类表单
     * @return type
     */
    public static function getSelectCate($value = '') {
        self::$selected = $value;
        $list = self::listCategory();
        self::setInputOption($list, $list);
        return self::$tree;
    }

    /**
     * 用于option表单输出
     * @param $array 数组一
     * @param $array_2 数组二
     * @param $id 父类产品ID
     * @param $depth 用于判断递归深度
     */
    private static function setInputOption($array, $array_2, $id = '0', $depth = '0') {
        $count = count($array_2);
        if ($depth < 3) {
            for ($i = 0; $i < $count; $i++) {
                if ($id == 0 && $array[$i]['parent_id'] == 0) {
                    $selected = self::$selected == $array[$i]['id'] ? 'selected="selected"' : '';
                    self::$tree .= '<option value="' . $array[$i]['id'] . '"' . $selected . '>' . $array[$i]['cate_name'] . '</option>';
                }
                foreach ($array as $key => $value) {
                    self::$li = 1;
                    if ($array[$i]['id'] == $value['parent_id'] && $array[$i]['parent_id'] == 0) {
                        $selected = self::$selected == $value['id'] ? 'selected="selected"' : '';
                        self::$tree .= '<option value="' . $value['id'] . '"' . $selected . '>' . self::nbsp(self::$li) . '└─' . $value['cate_name'] . '</option>';
                        self::setInputOption($array[$i], $array_2, $value['id'], 3);
                    }
                }
            }
        } elseif ($depth >= 3) {
            foreach ($array_2 as $depth_key => $depth_value) {
                if ($id == $depth_value['parent_id'] && $id > 0) {
                    $selected = self::$selected == $depth_value['id'] ? 'selected="selected"' : '';
                    self::$li++;
                    self::$tree .= '<option value="' . $depth_value['id'] . '"' . $selected . '>' . self::nbsp(self::$li) . '└─' . $depth_value['cate_name'] . '</option>';
                    self::setInputOption($array[$i], $array_2, $depth_value['id'], 3);
                    self::$li--;
                }
            }
        }
    }

    /**
     * 列出所有子类的ID(含父类)
     * @param type $id 父类的ID
     */
    public static function listChildId($id) {
        self::$tree = $id;
        self::findChildId($id);
        return self::$tree;
    }

    /**
     * 查找符合的子分类
     * @param $array 数组一
     * @param $array_2 数组二
     * @param $id 父类产品ID
     * @param $depth 用于判断递归深度
     */
    private static function findChildId($id) {
        $db = self::db('category');
        $result = $db->where('parent_id = :parent_id')->select(array('parent_id'=>$id));
        if(!empty($result)){
            foreach($result as $key => $value){
                self::$tree .= ','.$value['id'];
                self::findChildId($value['id']);
            }
        }
    }

}